<template>
	<div :class="curClassName" :style="curStyle">
		<img :src="imgUrl" />
	</div>
</template>
<script setup lang="ts">
import { ImgurlBase64 } from '@/core/utils/imgurl-base64';
import { FieldImageDynamicProps } from './field-image-dynamic';
const props = defineProps(FieldImageDynamicProps);

/**
 * 项名称
 *
 * @memberof FieldImageDynamic
 */
const itemName = computed(() => {
	return props.index || props.index === 0
		? `${props.name}_${props.index}`
		: props.name;
});

/**
 * 当前容器样式
 *
 * @memberof FieldImageDynamic
 */
const curStyle = computed(() => {
	const layoutModel = props.layoutModelDetails[itemName.value];
	if (layoutModel) {
		return layoutModel.getElementStyle();
	}
});

/**
 * 类名
 *
 * @memberof FieldImageDynamic
 */
const curClassName = computed(() => {
	const layoutModel = props.layoutModelDetails[itemName.value];
	if (layoutModel) {
		return `app-field-image-dynamic ${itemName.value} ${
			layoutModel.sysCss || ''
		}`;
	}
});

/**
 * 动态图片路径
 *
 * @memberof AppFieldImageDynamic
 */
const dynaImgUrl = ref('');

/**
 * 下载文件路径
 *
 * @memberof AppFieldImageDynamic
 */
const downloadUrl = App.getProjectSetting().exportFileUrl;

/**
 * 处理动态图片
 *
 * @memberof AppFieldImageDynamic
 */
const handleDynaImg = () => {
	if (props.value && typeof props.value == 'string') {
		// 默认识别文件对象形式，识别失败则为全路径模式
		try {
			const _files = JSON.parse(props.value);
			const file = _files instanceof Array ? _files[0] : null;
			const url = file && file.id ? `${downloadUrl}/${file.id}` : '';
			ImgurlBase64.getInstance()
				.getImgURLOfBase64(url)
				.then((res: any) => {
					dynaImgUrl.value = res;
				});
		} catch (error) {
			dynaImgUrl.value = props.value;
		}
	}
};

watch(
	() => props.value,
	() => {
		handleDynaImg();
	}
);

const imgUrl = computed(() => {
	return dynaImgUrl.value;
});
</script>
